/*
 * @Author: Jimmy
 * @LastModifiedBy: Jimmy
 * @Date: 2025-04-18 21:44:01
 * @LastEditTime: 2025-04-18 21:44:31
 * @FilePath: /lottery-box-react-master/src/utils/request.ts
 */
import axios, {
  AxiosInstance,
  AxiosRequestConfig,
  AxiosError,
  AxiosResponse,
} from "axios";
import { getCache, removeAll } from "./storage";
import { message } from "antd";

const service: AxiosInstance = axios.create({
  baseURL: import.meta.env.VITE_API_URL,
  timeout: 60 * 1000 * 20,
});

// 请求处理
service.interceptors.request.use(
  (config: any) => {
    let token = getCache("User")?.token || getCache("token");
    config.params = {
      ...config.params,
      token: token,
    };
    config.headers = {
      token: token,
    };
    return config;
  },
  (error: AxiosError) => {
    return Promise.reject(error);
  }
);
//响应处理
service.interceptors.response.use(
  (response: AxiosResponse) => {
    return Promise.resolve(response.data);
  },
  (error: any) => {
    message.destroy();
    if (error && error.response) {
      switch (error.response.status) {
        case 401:
          message.error("未授权");
          window.location.href = "/login";
          removeAll();
          break;
        default:
          message.error(
            error.response.data.detail || error.response.data.msg || "请求错误"
          );
          // message.error(
          //   error.response.data.message || error.response.data.msg || "请求错误"
          // );
          break;
      }
    }
    return Promise.reject(error);
  }
);

export const http = {
  get<T = any>(url: string, config?: AxiosRequestConfig): Promise<T> {
    return service.get(url, config);
  },
  delete<T = any>(url: string, config?: AxiosRequestConfig<T>): Promise<T> {
    return service.delete(url, config);
  },
  post<T = any>(
    url: string,
    data?: object,
    config?: AxiosRequestConfig
  ): Promise<T> {
    return service.post(url, data, config);
  },
  put<T = any>(
    url: string,
    data?: object,
    config?: AxiosRequestConfig
  ): Promise<T> {
    return service.put(url, data, config);
  },
  patch<T = any>(
    url: string,
    data?: object,
    config?: AxiosRequestConfig
  ): Promise<T> {
    return service.patch(url, data, config);
  },
};

export default service;
